package com.study.lxy.netty.nio;

import com.alibaba.fastjson.JSON;
import com.study.lxy.netty.dto.ResponseData;
import com.study.lxy.netty.util.ResponseBuilder;
import com.sun.corba.se.spi.activation.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class SimpleServer {
    public static void main(String[] args) throws Exception {
        Thread t = new Thread(new SimpleServerRunner(8080));
        t.start();
        t.join();
    }
}

class SimpleServerRunner implements Runnable {
    private volatile boolean stop;
    private ServerSocketChannel socketChannel;
    private Selector selector;
    private static final Logger logger = LoggerFactory.getLogger(SimpleServerRunner.class);
    public SimpleServerRunner(int port) throws Exception {
        socketChannel = ServerSocketChannel.open();
        socketChannel.socket().bind(new InetSocketAddress(port));
        socketChannel.configureBlocking(false);
        //
        selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);
    }

    public void stop(){
        stop = true;
    }

    public void run() {
        while (!stop){
            try {
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    try {
                        handlerInput(key);
                    } catch (Exception e){
                        if(key != null){
                            key.cancel();
                            if(key.channel() != null){
                                key.channel().close();
                            }
                        }
                    }
                }

            } catch (Exception e){
                e.printStackTrace();
                System.exit(-1);
            }
        }
    }

    private void handlerInput(SelectionKey key) throws Exception{
        logger.info("accept event....");
        if(key.isValid()){
            if(key.isAcceptable()){
                logger.info("accept a connect");
                ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                SocketChannel sc = ssc.accept();
                sc.configureBlocking(false);
                sc.register(selector, SelectionKey.OP_READ);
                writeData(sc, "welcome!");
            }

            if(key.isReadable()){
                SocketChannel sc = (SocketChannel) key.channel();
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                int size = sc.read(byteBuffer);
                if(size > 0){
                    byteBuffer.flip();
                    byte[] bytes = new byte[byteBuffer.remaining()];
                    byteBuffer.get(bytes);
                    String data = new String(bytes, "UTF-8");
                    logger.info("message received : {}", data);
                    ResponseData<String> responseData = ResponseBuilder.build(data);
                    String respStr = JSON.toJSONString(responseData);
                    logger.info("message return : {}", respStr);
                    writeData(sc, respStr);
                } else if(size < 0){
                    key.cancel();
                    sc.close();
                }
            }
        }

    }

    /**
     * 将数据输出到SocketChannel
     * @param sc
     * @param data
     * @throws Exception
     */
    private void writeData(SocketChannel sc, String data) throws Exception{
        byte[] respBytes = data.getBytes();
        ByteBuffer outBuffer = ByteBuffer.allocate(respBytes.length);
        outBuffer.put(respBytes);
        outBuffer.flip();
        sc.write(outBuffer);
    }
}
